# 将dict数据写入excel
# 例如 [{'star_num':'','link':'','content':''},{},{},{}]
import os
import openpyxl
import json
def find_excel():
    tar_list=[]
    origin_list=[]
    # 查找excel文件
    now_path=os.getcwd().replace('\\write_excel','')
    try:
        ll=os.listdir(now_path)
        for c in ll:
            if('.' not in c):
                temp=os.listdir(now_path+'\\'+c)
                for ff in temp:
                    t_dict={}
                    t_dict['filename']=ff
                    t_dict['path']=now_path+'\\'+c+'\\'+ff
                    origin_list.append(t_dict)
    except:
        pass
    #print(origin_list)
    for each in origin_list:
        if 'json' in each['filename']:
            tar_list.append(each)
    print('Please choose file:')
    for c in tar_list:
        print(' {} : {} '.format(tar_list.index(c),c['filename']))
    xuhao=int(input('choose:'))
    return tar_list[xuhao]['path']


def write_excel(path):
    temp_list=str(path).split('\\')
    filename=temp_list[len(temp_list)-1].split('.')[0]
    print(filename)
    with open(path,'r',encoding='utf8') as file:
        data=json.load(file)
    wb = openpyxl.Workbook()
    book=wb.active
    count=1
    #print(data)
    top_list=[]
    for key in data[0].keys():
        top_list.append(key)
        book.cell(row=1,column=count).value=key
        count+=1
    for each in data:
        count=1
        for valuee in each.values():
            valuee=str(valuee).strip('\n').strip(' ')
            book.cell(row=2+data.index(each),column=count).value=valuee
            count+=1
    print('OVER!')
    wb.save('{}.xlsx'.format(filename))

if __name__ == '__main__':
    path=find_excel()
    write_excel(path)